package team.travel.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import team.travel.User;
import team.travel.dao.UserDao;
import team.travel.inforsecurity.EncryptionUtil;
/**
 * 用户注册的Servlet类
 * @author KangJingbo
 */
public class RegisterServlet extends HttpServlet {
	private static final long serialVersionUID = 5280356329609002908L;

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		
		// 获取用户名
		String username = request.getParameter("username");
		int id = Integer.parseInt(username);
		//获取姓名
		String name = request.getParameter("user");
		// 获取密码
		String password = EncryptionUtil.MD5(request.getParameter("password"));
		// 获取性别
		String sex = request.getParameter("sex");
		// 获取QQ
		String qq = request.getParameter("qq");
		// 获取联系电话
		String phone = request.getParameter("phone");

		// 实例化UserDao对象
		UserDao userDao = new UserDao();
		if(username != null && !username.isEmpty()){
			if(userDao.userIsExist(id)){
				// 实例化一个User对象
				User user = new User();		
				// 对用户对象中的属性赋值
				user.setId(id);	
				user.setSex(sex);
				user.setName(name);
				user.setPhone(phone);
				user.setQq(qq);
				
				// 保存用户注册信息
				userDao.saveUser(user);	
				request.setAttribute("info", "恭喜，注册成功！<br>");
				request.setAttribute("tag", 1);
				
				UserDao tempuserDao = new UserDao();
				User tempuser = null;
				tempuser = tempuserDao.login(id, password);
				request.setAttribute("userInfo", tempuser);
			}else{
				request.setAttribute("info", "错误：此学号已被注册！<br>");
				request.setAttribute("tag", 0);
			}
		}
		// 转发到message.jsp页面
		request.getRequestDispatcher("webpage/result.jsp").forward(request, response);
	}

}
